//package com.root.dreameraadmin.activity;
//
//import android.app.Activity;
//import android.app.AlertDialog;
//import android.content.ContentResolver;
//import android.content.Context;
//import android.content.DialogInterface;
//import android.content.Intent;
//import android.database.Cursor;
//import android.graphics.Bitmap;
//import android.graphics.BitmapFactory;
//import android.net.Uri;
//import android.os.Bundle;
//import android.os.Handler;
//import android.os.Message;
//import android.provider.MediaStore;
//import android.util.Log;
//import android.view.View;
//import android.widget.AdapterView;
//import android.widget.Button;
//import android.widget.EditText;
//import android.widget.ImageView;
//import android.widget.Spinner;
//import android.widget.TextView;
//import android.widget.Toast;
//
//import com.google.android.gms.appindexing.AppIndex;
//import com.google.android.gms.common.api.GoogleApiClient;
//import com.root.dreameraadmin.R;
//import com.root.dreameraadmin.utils.HttpConnectionUtil;
//
//import java.io.ByteArrayInputStream;
//import java.io.ByteArrayOutputStream;
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.FileNotFoundException;
//import java.io.InputStream;
//import java.util.HashMap;
//
//
///**
// * Created by root on 16-7-1.
// */
//public class AddPictureActivity extends Activity {
//
//    private final static String TAG = "AddPictureActivity";
//
//    private EditText picture_title_EditText;
//
//    private EditText picture_datetime_EditText;
//    private Spinner picture_datetime_Spinner;
//    private EditText picture_time_str_EditText;
//    private EditText picture_like_count_EditText;
//    private EditText picture_detail_url_EditText;
//    private TextView picture_location_TextView;
//    private EditText picture_detail_title_EditText;
//    private Button clear;
//    private Button submit;
//    private ImageView picture_imageview;
//
//    private Bitmap picture_map;
//
//    private String picture_title;
//    private String picture_longitude;
//    private String picture_latitude;
//    private int point_id;
//    File file;
//
//    private String file_path;
//
//    public static final int UPDATE_TEXT = 1;
//
//    private boolean flag=false;
//    HashMap<String, Object> pic_map = new HashMap<String, Object>();
//
//    private String picture_path;
//    private Bitmap picFromFile;
//
//    /**
//     * ATTENTION: This was auto-generated to implement the App Indexing API.
//     * See https://g.co/AppIndexing/AndroidStudio for more information.
//     */
//    private GoogleApiClient client;
//
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        Log.d(TAG, "onCreate");
//        setContentView(R.layout.picture_add_activity);
//        //bind
//
//        Intent i = new Intent();
//        i.setType("image/*");
//        i.setAction(Intent.ACTION_GET_CONTENT);
//        startActivityForResult(i,1);
//
//        picture_imageview = (ImageView) findViewById(R.id.picture_show);
//        picture_title_EditText = (EditText) findViewById(R.id.picture_title);
//        picture_datetime_EditText = (EditText) findViewById(R.id.picture_datetime);
//        picture_datetime_Spinner = (Spinner) findViewById(R.id.picture_datetime_Spinner);
//        picture_time_str_EditText = (EditText) findViewById(R.id.picture_time_str);
//        picture_like_count_EditText = (EditText) findViewById(R.id.picture_like_count);
//        picture_detail_url_EditText = (EditText) findViewById(R.id.picture_detail_url);
//        picture_location_TextView = (TextView) findViewById(R.id.picture_location);
//        picture_detail_title_EditText = (EditText) findViewById(R.id.picture_detail_title);
//        submit = (Button) findViewById(R.id.submit);
//        clear = (Button) findViewById(R.id.clear);
//
//        // picture_datetime_Spinner.set
//
//        //get and set data
//        Intent intent = getIntent();
//        Bundle bundle = intent.getExtras();
//        point_id = bundle.getInt("point_id");
////        file_path = bundle.getString("picture_path");
////        picture_longitude = bundle.getString("longitude");
////        picture_latitude = bundle.getString("latitude");
//
//        //get picture
//        /*
//        file = new File(file_path);
//
//        Log.d(TAG, "the file_path is:" + file_path);
//        Log.d(TAG, "the file name is:" + file.getName());
//        InputStream is = null;
//        if (file.exists()) {
//            Log.d(TAG, "file exits");
//        }
//        try {
//            is = new FileInputStream(file);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//
//
//        picture_map = BitmapFactory.decodeStream(is);
//        */
////        Log.d(TAG, "the picture_map is :" + picture_map.getByteCount());
////        Log.d(TAG, "the height and the width is" + picture_map.getHeight() + "," + picture_map.getWidth());
////        Log.d(TAG, "the picture_map is " + picture_map);
////        Log.d(TAG, "set picture to imageView");
//
//        // ATTENTION: This was auto-generated to implement the App Indexing API.
//        // See https://g.co/AppIndexing/AndroidStudio for more information.
//        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
//    }
//
//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (resultCode == RESULT_OK) {
//            Uri uri;
//            uri = data.getData();
//            //file_path=uri.getPath();
//            Log.d(TAG, uri.toString());
//            picture_path = getRealFilePath(AddPictureActivity.this, uri);
//            Log.d(TAG, "picture_path is " + picture_path);
//            ContentResolver cr = this.getContentResolver();
//            try {
//                picFromFile = BitmapFactory.decodeStream(cr.openInputStream(uri));
//
//                Log.d(TAG,"the count of picture is"+picFromFile.getByteCount());
//                Log.d(TAG,"before compress the with and height is "+picFromFile.getHeight()+":"+picFromFile.getWidth());
//                if(picFromFile.getHeight()>1000||picFromFile.getWidth()>1000){
////                  picFromFile.compress(Bitmap.CompressFormat.JPEG,50,fileOutputStream);
//                   picture_map=compressBmpFromBmp(picFromFile);
//                    Log.d(TAG,"After compress the with and height is "+picFromFile.getHeight()+":"+picFromFile.getWidth());
//                    Log.d(TAG,"the count of picture is"+picFromFile.getByteCount());
//                    Log.d(TAG,"after compress the count of picture is "+picFromFile.getByteCount());
//                }else {picture_map=picFromFile;}
////                Log.d(TAG,"before compress is"+picFromFile.getByteCount());
////                CompressPicture(picFromFile);
////                Log.d(TAG,"After compress is"+picFromFile.getByteCount());
//                //picFromFile.compress(CompressFormat.JPEG, 80);
//                Log.d(TAG, "picture_map is " + picFromFile.toString());
//            } catch (FileNotFoundException e) {
//                Log.e(TAG, e.getMessage(), e);
//            }
//        }
//        super.onActivityResult(requestCode, resultCode, data);
//    }
//
//    public  String getRealFilePath(final Context context, final Uri uri) {
//        if (null == uri) return null;
//        final String scheme = uri.getScheme();
//        String data = null;
//        if (scheme == null)
//            data = uri.getPath();
//        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
//            data = uri.getPath();
//        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
//            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
//            if (null != cursor) {
//                if (cursor.moveToFirst()) {
//                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
//                    if (index > -1) {
//                        data = cursor.getString(index);
//                    }
//                }
//                cursor.close();
//            }
//        }
//        return data;
//    }
//    private Bitmap compressBmpFromBmp(Bitmap image){
//
//        ByteArrayOutputStream out = new ByteArrayOutputStream();
//        image.compress(Bitmap.CompressFormat.JPEG, 10, out);
//        BitmapFactory.Options newOpts =  new  BitmapFactory.Options();
//        int be = 3;
//        newOpts.inSampleSize = be;
//        ByteArrayInputStream isBm =  new  ByteArrayInputStream(out.toByteArray());
//        image = BitmapFactory.decodeStream(isBm,  null ,  null );
//        return image;
//    }
//
//
//    @Override
//    protected void onStart() {
//        super.onStart();
//        Log.d(TAG, "onStart");
//    }
//
//    @Override
//    protected void onResume() {
//        super.onResume();
//        Log.d(TAG, "onResume");
//
////
////        LatLng sourceLatLng = new LatLng(Double.parseDouble(picture_latitude), Double.parseDouble(picture_longitude));
////        // 将GPS设备采集的原始GPS坐标转换成百度坐标
////        CoordinateConverter converter = new CoordinateConverter();
////        converter.from(CoordinateConverter.CoordType.GPS);
////        // sourceLatLng待转换坐标
////        converter.coord(sourceLatLng);
////        LatLng desLatLng = converter.convert();
////
//
////        picture_location_TextView.setText(desLatLng.longitude + "\n" + desLatLng.latitude);
//
//        picture_imageview.setImageBitmap(picture_map);
////         picture_location_TextView.setText(picture_longitude+"\n"+picture_latitude);
//
//        picture_datetime_Spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view,
//                                       int pos, long id) {
//
//                String[] languages = getResources().getStringArray(R.array.languages);
//                picture_datetime_EditText.setText(languages[pos]);
//                // Toast.makeText(AddPictureActivity.this, "你点击的是:"+languages[pos],Toast.LENGTH_LONG).show();
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//                // Another interface callback
//            }
//        });
//        final Handler handler = new Handler() {
//            public void handleMessage(Message msg) {
//                switch (msg.what) {
//                    case UPDATE_TEXT:
//                        finish();
//                        break;
//                    default:
//                        break;
//                }
//            }
//        };
//
//        submit.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Log.d(TAG, "start upload picture ");
//
//                //file=new File(file_path);
//                Log.d(TAG, "file name is" + file.getName());
//
//                if (picture_title_EditText.getText().toString().equals("") || picture_time_str_EditText.getText().toString().equals("")) {
//                    Toast.makeText(AddPictureActivity.this, "title\ntime_str\ndatetime\nCan not be null!", Toast.LENGTH_SHORT).show();
//                } else {
//                    pic_map.put("title", picture_title_EditText.getText().toString());
//                    // pic_map.put("picture",file);
//                    pic_map.put("datetime", picture_datetime_EditText.getText().toString() + "-01-01T01:01:00Z");
//                    pic_map.put("time_str", picture_time_str_EditText.getText().toString());
//                    pic_map.put("detail_url", picture_detail_url_EditText.getText().toString());
//                    pic_map.put("detail_title", picture_detail_title_EditText.getText().toString());
//                    pic_map.put("like_count", picture_like_count_EditText.getText().toString());
//                    pic_map.put("longitude", picture_longitude);
//                    pic_map.put("latitude", picture_latitude);
//                    pic_map.put("altitude", 0);
//                    pic_map.put("place", point_id);
//
//                    Log.d(TAG, "pic_map is " + pic_map.toString());
//                    new AlertDialog.Builder(AddPictureActivity.this).setTitle("系统提示")//设置对话框标题
//                            .setMessage("ADD this picture?")//设置显示的内容
//                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {//添加确定按钮
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
//                                    //new thread to add
//                                    Toast.makeText(AddPictureActivity.this,"正在上传，请稍候！",Toast.LENGTH_LONG).show();
//                                    new Thread() {
//                                        public void run() {
//                                            try {
//                                                HttpConnectionUtil.doPostPicture(HttpConnectionUtil.PICTUREURl, pic_map, file);
//                                                runOnUiThread(new Runnable() {
//                                                    @Override
//                                                    public void run() {
//                                                        if (HttpConnectionUtil.result=="success") {
//                                                            Toast.makeText(AddPictureActivity.this, "上传成功！", Toast.LENGTH_SHORT).show();
//                                                            Message message = new Message();
//                                                            message.what = UPDATE_TEXT;
//                                                            handler.sendMessage(message);
//                                                            // pic_map.clear();
//                                                        } else {
//                                                            Toast.makeText(AddPictureActivity.this, "上传失败！", Toast.LENGTH_SHORT).show();
//                                                            //pic_map.clear();
//                                                        }
//                                                    }
//                                                });
//                                            } catch (Exception e) {
//                                                e.printStackTrace();
//                                            }
//                                        }
//                                    }.start();
//                                }
//                            })
//                            .setNegativeButton("No", new DialogInterface.OnClickListener() {//添加返回按钮
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {//响应事件
//                                    // TODO Auto-generated method stub
//                                    dialog.dismiss();
//                                }
//                            }).show();//在按键响应事件中显示此对话框
//                }
//            }
//        });
//
//        clear.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                picture_title_EditText.setText("");
//                picture_datetime_EditText.setText("");
//                picture_time_str_EditText.setText("");
//                picture_detail_url_EditText.setText("");
//                picture_detail_title_EditText.setText("");
//                picture_like_count_EditText.setText("");
//            }
//        });
//    }
//
//    @Override
//    protected void onPause() {
//        super.onPause();
//        Log.d(TAG, "onPause");
//    }
//
//    @Override
//    protected void onStop() {
//        super.onStop();
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        Log.d(TAG, "onDestroy");
//        if (!picture_map.isRecycled()) {
//            picture_map.recycle();
//        }
//    }
//    @Override
//    protected void onRestart() {
//        super.onRestart();
//        Log.d(TAG, "onRestart");
//    }
//
////    public GeoPoint gpsToBaidu(String data) {
////        String[] p = data.split(",");
////        int lat = (int) (((int) (Float.valueOf(p[0]) / 100) + (100 * (Float.valueOf(p[0]) / 100.0 - (int) (Float.valueOf(p[0]) / 100)) / 60.0)) * 1E6);
////        int lon = (int) (((int) (Float.valueOf(p[1]) / 100) + (100 * (Float.valueOf(p[1]) / 100.0 - (int) (Float.valueOf(p[1]) / 100)) / 60.0)) * 1E6);
////        GeoPoint pt = new GeoPoint(lat, lon);
////        return CoordinateConverter.;
////    }
//}


package com.root.dreameraadmin.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.root.dreameraadmin.R;
import com.root.dreameraadmin.utils.HttpConnectionUtil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.root.dreameraadmin.view.ToolBarView.startIntroAnimation;


/**
 * Created by root on 16-7-1.
 */
public class AddPictureActivity extends AppCompatActivity {

    private final static String TAG = "AddPictureActivity";

    @Nullable
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.toolbar_text)
    TextView toolbar_textView;
    @Bind(R.id.ib_map)
    Button mapBtn;
    @Bind(R.id.picture_show)
    ImageView picture_imageview;   //图片
    @Bind(R.id.picture_title)
    EditText picture_title_EditText;  //title编辑框
    @Bind(R.id.picture_datetime)
    EditText picture_datetime_EditText;  //datetime编辑框
    @Bind(R.id.picture_datetime_Spinner)
    Spinner picture_datetime_Spinner;   //下拉菜单
    @Bind(R.id.picture_time_str)
    EditText picture_time_str_EditText; //time_str编辑框
    @Bind(R.id.picture_detail_url)
    EditText picture_detail_url_EditText; //detail_url编辑框

    private Bitmap picture_map;
    private int point_id;
    File file;
    public static final int UPDATE_TEXT = 1;
    HashMap<String, Object> pic_map = new HashMap<String, Object>();
    private String picture_path;
    private Bitmap picFromFile;
    private ProgressDialog progressDialog=null;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        setContentView(R.layout.picture_add_activity);
        ButterKnife.bind(this);

        mapBtn.setVisibility(View.GONE);

        Intent i = new Intent();
        i.setType("image/*");
        i.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(i,1);

        //get and set data
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        point_id = bundle.getInt("point_id");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        setSupportActionBar(toolbar);
        startIntroAnimation(toolbar, toolbar_textView, "添加图片");


        System.out.println("asdf resultCode "+ resultCode);
        if (resultCode == RESULT_OK) {
            Uri uri;
            uri = data.getData();
            picture_path = getRealFilePath(AddPictureActivity.this, uri);

            try {
                file = new File(picture_path);
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                int size =  fis.available();
                if(size/1024.0/1024.0 >= 0.5) {
                    Toast.makeText(AddPictureActivity.this,
                            "图片大小不能超过0.5M", Toast.LENGTH_SHORT).show();
                    finish();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            ContentResolver cr = this.getContentResolver();

            try {
                picFromFile = BitmapFactory.decodeStream(cr.openInputStream(uri));
                if(picFromFile.getHeight() > 1000 || picFromFile.getWidth() > 1000){
                    picture_map = compressBmpFromBmp(picFromFile);
                }else {
                    picture_map = picFromFile;
                }

                picture_imageview.setImageBitmap(picture_map);

            } catch (FileNotFoundException e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }else if(resultCode == RESULT_CANCELED) {
            finish();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public  String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    private Bitmap compressBmpFromBmp(Bitmap image){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 10, out);
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        int be = 3;
        newOpts.inSampleSize = be;
        ByteArrayInputStream isBm = new ByteArrayInputStream(out.toByteArray());
        image = BitmapFactory.decodeStream(isBm,  null ,  null );
        return image;
    }


    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");

//        picture_imageview.setImageBitmap(picture_map);

        picture_datetime_Spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {

                String[] languages = getResources().getStringArray(R.array.languages);
                picture_datetime_EditText.setText(languages[pos]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
    }



    @OnClick(R.id.submit)
    public void clickSubmit() {

        if (picture_title_EditText.getText().toString().equals("")
                || picture_time_str_EditText.getText().toString().equals("")) {
            Toast.makeText(AddPictureActivity.this,
                    "信息不完整哦~", Toast.LENGTH_SHORT).show();
            return ;
        }
        pic_map.put("title", picture_title_EditText.getText().toString());
        pic_map.put("datetime", picture_datetime_EditText.getText().toString() + "-01-01T01:01:00Z");
        pic_map.put("time_str", picture_time_str_EditText.getText().toString());
        pic_map.put("detail_url", picture_detail_url_EditText.getText().toString());
        pic_map.put("place", point_id);

        new AlertDialog.Builder(AddPictureActivity.this)
                .setMessage("要添加这个图片吗")//设置显示的内容
                .setPositiveButton("添加", positiveListener)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//响应事件
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                    }
                }).show();//在按键响应事件中显示此对话框
    }



    Thread thread = new Thread(){
        public void run() {
            //这里处理耗时操作，上传图片
            try {
                HttpConnectionUtil.doPostPicture(HttpConnectionUtil.PICTUREURl, pic_map, file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            handler.sendEmptyMessage(0);
        }
    };

    final Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            progressDialog.dismiss();
            if (HttpConnectionUtil.result == "success") {
                Toast.makeText(AddPictureActivity.this, "上传成功！", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                Toast.makeText(AddPictureActivity.this, "上传失败！", Toast.LENGTH_SHORT).show();
            }
            super.handleMessage(msg);
        }
    };


    public DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener(){

        @Override
        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
            //new thread to add
            progressDialog = ProgressDialog.show(AddPictureActivity.this, "","正在上传中...",true);
            thread.start();
        }
    };

    @OnClick(R.id.clear)
    public void clickClear() {
        picture_title_EditText.setText("");
        picture_datetime_EditText.setText("");
        picture_time_str_EditText.setText("");
        picture_detail_url_EditText.setText("");
    }



    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        if (picture_map != null && !picture_map.isRecycled()) {
            picture_map.recycle();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart");
    }

    @OnClick(R.id.ib_back)
    public void clickBack() {
        finish();
    }

}